<template>
  <transition>
    <div class="backtop" v-show="backShow">
      <img src="./backtop.png" @click="backTop" />
    </div>
  </transition>
</template>

<script>
import { getRealHeight } from "@/utils/dom";
import { mapGetters, mapActions } from "vuex";
import { throttle } from "lodash";

export default {
  props: {
    height: {
      type: Number,
      default: 500
    },
    duration: {
      type: Number,
      default: 300
    }
  },
  data() {
    return {
      backShow: false,
      dom: null
    };
  },
  computed: {
    ...mapGetters(["scrollTop"])
  },
  watch: {
    scrollTop(val) {
      this.backShow = val >= getRealHeight(this.height);
    }
  },
  methods: {
    ...mapActions(["setScrollTop"]),
    backTop() {
      let scrollTop = this.scrollTop;
      const doc = document;
      for (let i = 60; i >= 0; i--) {
        setTimeout(
          i => {
            let val = (scrollTop * i) / 60;
            doc.documentElement.scrollTop = val;
            doc.body.scrollTop = val;
          },
          (this.duration / 60) * (60 - i),
          i
        );
      }
    }
  },
  created() {
    // scroll top
    const doc = document;
    doc.addEventListener(
      "scroll",
      throttle(() => {
        const scrollTop = doc.documentElement.scrollTop || doc.body.scrollTop;
        this.setScrollTop(scrollTop);
      }, 50)
    );
  }
};
</script>

<style lang="less" scoped>
.backtop {
  position: fixed;
  bottom: 62px;
  right: 4px;
  z-index: 5;
  opacity: 0.88;

  &.v {
    &-enter-active,
    &-leave-active {
      transition: all @transition-time;
    }

    &-enter,
    &-leave-to {
      opacity: 0;
    }
  }

  img {
    width: 58px;
  }
}
</style>
